import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { Message } from '@arco-design/web-vue'
import { authApi, userApi } from '@/api'
import type { LoginRequest } from '@/api/auth'

// 用户信息接口
interface UserInfo {
  id: number
  username: string
  realName: string
  nickname: string
  avatar?: string
  email?: string
  phone?: string
  deptName?: string
  roles?: Array<{
    id: number
    roleName: string
    roleCode: string
  }>
  permissions?: string[]
}

// 登录表单接口
interface LoginForm {
  username: string
  password: string
  captchaCode?: string
  captchaId?: string
  rememberMe?: boolean
}

export const useUserStore = defineStore('user', () => {
  // 状态
  const token = ref<string>(localStorage.getItem('token') || '')
  const userInfo = ref<UserInfo | null>(null)
  const permissions = ref<string[]>([])
  const roles = ref<string[]>([])

  // 计算属性
  const isLoggedIn = computed(() => !!token.value)
  const hasPermission = (permission: string) => {
    return permissions.value.includes(permission) || permissions.value.includes('*:*:*')
  }
  const hasRole = (role: string) => {
    return roles.value.includes(role) || roles.value.includes('admin')
  }

  // 设置Token
  const setToken = (newToken: string) => {
    token.value = newToken
    localStorage.setItem('token', newToken)
  }

  // 清除Token
  const clearToken = () => {
    token.value = ''
    localStorage.removeItem('token')
  }

  // 设置用户信息
  const setUserInfo = (info: UserInfo) => {
    userInfo.value = info
    
    // 设置权限和角色
    if (info.permissions) {
      permissions.value = info.permissions
    }
    if (info.roles) {
      roles.value = info.roles.map(role => role.roleCode)
    }
  }

  // 清除用户信息
  const clearUserInfo = () => {
    userInfo.value = null
    permissions.value = []
    roles.value = []
  }

  // 登录
  const login = async (loginForm: LoginForm) => {
    try {
      const response = await authApi.login(loginForm)
      
      if (response.data) {
        const { token: userToken, user } = response.data
        setToken(userToken)
        setUserInfo(user)
        
        Message.success('登录成功')
        return { success: true, data: response.data }
      }
      
      throw new Error('登录响应数据异常')
    } catch (error: any) {
      Message.error(error.message || '登录失败')
      throw error
    }
  }

  // 登出
  const logout = async () => {
    try {
      if (token.value) {
        await authApi.logout()
      }
    } catch (error: any) {
      console.error('登出API调用失败:', error)
      // 即使后端API失败，也要继续清除本地数据
    } finally {
      // 无论API调用成功与否，都要清除本地数据
      clearToken()
      clearUserInfo()
      
      // 清除其他可能的缓存数据
      localStorage.removeItem('menuCollapsed')
    }
    
    return { success: true }
  }

  // 获取用户信息
  const getUserInfo = async () => {
    if (!token.value) {
      throw new Error('未登录')
    }

    try {
      // 如果已经有用户信息，直接返回
      if (userInfo.value) {
        return userInfo.value
      }

      const response = await authApi.getUserInfo()
      
      if (response.data) {
        setUserInfo(response.data)
        return response.data
      }
      
      throw new Error('获取用户信息失败')
    } catch (error: any) {
      console.error('获取用户信息失败:', error)
      // 如果获取用户信息失败，可能token已过期
      await logout()
      throw error
    }
  }

  // 更新用户信息
  const updateUserInfo = async (data: Partial<UserInfo>) => {
    try {
      await userApi.updateProfile(data)
      
      // 更新本地数据
      if (userInfo.value) {
        Object.assign(userInfo.value, data)
      }
      
      Message.success('更新成功')
      return { success: true }
    } catch (error: any) {
      Message.error(error.message || '更新失败')
      throw error
    }
  }

  // 修改密码
  const changePassword = async (data: { oldPassword: string; newPassword: string }) => {
    try {
      await userApi.changePassword(data.oldPassword, data.newPassword)
      
      Message.success('密码修改成功，请重新登录')
      await logout()
      return { success: true }
    } catch (error: any) {
      Message.error(error.message || '密码修改失败')
      throw error
    }
  }

  return {
    // 状态
    token,
    userInfo,
    permissions,
    roles,
    
    // 计算属性
    isLoggedIn,
    hasPermission,
    hasRole,
    
    // 方法
    setToken,
    clearToken,
    setUserInfo,
    clearUserInfo,
    login,
    logout,
    getUserInfo,
    updateUserInfo,
    changePassword
  }
}, {
  persist: {
    key: 'user-store',
    storage: localStorage,
    paths: ['token', 'userInfo', 'permissions', 'roles']
  }
}) 